package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrateCommentQueryObject;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentMongoRepository repository;

    @Override
    public void save(StrategyComment comment) {
        //填充创建时间
        comment.setCreateTime(new Date());
        repository.save(comment);

    }

    @Override
    public Page<StrategyComment> findByDetailId(StrateCommentQueryObject qo) {
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        return repository.findByDetailId(qo.getDetailId(), pageable);
    }

    @Override
    public void commentThumbUp(String toId, Long formId) {
        //根据id查询评论
        Optional<StrategyComment> op = repository.findById(toId);
        op.ifPresent(comment -> {
            //获取点赞的集合
            List<Long> thumbuplist = comment.getThumbuplist();
            //判断集合中是否包含点赞的用户id  formId,如果没有就是点赞,如果有就是取消点赞
            if (thumbuplist.contains(formId)) {
                //取消点赞
                thumbuplist.remove(formId);
                comment.setThumbupnum(comment.getThumbupnum() - 1);
            } else {
                //点赞
                thumbuplist.add(formId);
                comment.setThumbupnum(comment.getThumbupnum() + 1);
            }
            comment.setThumbuplist(thumbuplist);
            //保存到评论对象
            repository.save(comment);
        });
    }

}
